package com.edroid.apkhooker.db;

import java.io.IOException;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * 机型数据库
 * 
 * @author zengming 2014/12/16
 *
 */
public class ModelDB {
	public static class Model {
		public int _id;
		public String model;
		public String manufacturer;
		public String hardware;
		public String brand;
		public String board;
		public String release;
		public String baseband;
		public String screen;

		public Model(int _id, String model, String manufacturer,
				String hardware, String brand, String board, String release,
				String baseband, String screen) {
			super();
			this._id = _id;
			this.model = model;
			this.manufacturer = manufacturer;
			this.hardware = hardware;
			this.brand = brand;
			this.board = board;
			this.release = release;
			this.baseband = baseband;
			this.screen = screen;
		}

		public Model() {
		}

		@Override
		public String toString() {
			return "Model [_id=" + _id + ", model=" + model + ", manufacturer="
					+ manufacturer + ", hardware=" + hardware + ", brand="
					+ brand + ", board=" + board + ", release=" + release
					+ ", baseband=" + baseband + ", screen=" + screen + "]";
		}

	}

	private static ModelDB modelDB;
	private Context context;
	private SQLiteDatabase db;
	private int modelTotal;

	private ModelDB() {
	}

	public static void init(Context context) throws IOException {
		if (modelDB == null) {
			modelDB = new ModelDB();
			modelDB.context = context;
			try {
				modelDB.db = SQLiteDatabase.openDatabase(
						AssetsReleaseTool.releaseFile(context, "models.db"),
						null, SQLiteDatabase.OPEN_READONLY);
				Cursor cursor = modelDB.db.rawQuery(
						"select count(*) from models", null);
				cursor.moveToFirst();
				modelDB.modelTotal = cursor.getInt(0);
				cursor.close();
			} catch (IOException exception) {
				modelDB = null;
				exception.printStackTrace();
				throw exception;
			}
		}
	}

	public static ModelDB getModelDB() {
		return modelDB;
	}

	public int getModelTotal() {
		return modelTotal;
	}

	/**
	 * 获得指定ID的机型数据
	 * 
	 * @param id
	 *            取值范围 [ 0 , {@link #getModelTotal()} )
	 * @return 机型数据
	 */
	public Model getModelById(int id) {
		Cursor cursor = db.rawQuery("select * from models where _id=" + id,
				null);
		Model model = null;
		if (cursor.moveToFirst()) {
			model = new Model();
			model._id = cursor.getInt(0);
			model.model = cursor.getString(1);
			model.manufacturer = cursor.getString(2);
			model.hardware = cursor.getString(3);
			model.brand = cursor.getString(4);
			model.board = cursor.getString(5);
			model.release = cursor.getString(6);
			model.baseband = cursor.getString(7);
			model.screen = cursor.getString(8);
		}
		cursor.close();
		return model;
	}

	public SQLiteDatabase getDatabase() {
		return db;
	}
	
	public static void close() {
		if (modelDB != null) {
			modelDB.db.close();
			modelDB = null;
		}
	}
}
